package com.xywl.escort.view.order.repo;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.xywl.escort.R;
import com.xywl.escort.adapter.RepoOrderAdapter;
import com.xywl.escort.base.BaseFragment;
import com.xywl.escort.bean.BaseResp;
import com.xywl.escort.bean.RepoOrderResp;
import com.xywl.escort.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import dagger.android.support.AndroidSupportInjection;
import timber.log.Timber;

/**
 * 认购订单-收购
 */
public class RepoOrderFragment extends BaseFragment implements RepoOrderContract.View, SwipeRefreshLayout.OnRefreshListener {
    private static final String ARG_PARAM1 = "param1";

    @BindView(R.id.recycler_order)
    RecyclerView mRecyclerOrder;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.progress_bar)
    ProgressBar mProgressBar;

    private RepoOrderAdapter mAdapter;
    private List<RepoOrderResp.DataBean.ListBean> mDataBeanList = new ArrayList<>();

    private int pageNum = 1;
    private boolean isEnd;

    @Inject
    RepoOrderContract.Presenter mPresenter;

    public RepoOrderFragment() {
        // Required empty public constructor
    }

    public static RepoOrderFragment newInstance(int param1) {
        RepoOrderFragment fragment = new RepoOrderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onAttach(Context context) {
        AndroidSupportInjection.inject(this);
        super.onAttach(context);
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_subscription_order;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        LinearLayoutManager manager = new LinearLayoutManager(this.getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerOrder.setLayoutManager(manager);

        mAdapter = new RepoOrderAdapter(R.layout.item_order_repo, mDataBeanList);
        mRecyclerOrder.setAdapter(mAdapter);

        View emptyView = LayoutInflater.from(this.getActivity()).inflate(R.layout.layout_empty_view, null);
        TextView tvEmpty = emptyView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂无数据");
        mAdapter.setEmptyView(emptyView);

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mSwipeRefreshLayout.setEnabled(false);
                mRecyclerOrder.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mSwipeRefreshLayout.setEnabled(false);
                        if (isEnd) {
                            //数据全部加载完毕
                            mAdapter.loadMoreEnd();
                            mSwipeRefreshLayout.setEnabled(true);
                        } else {
                            //成功获取更多数据
                            mPresenter.loadRepoOrderList(pageNum);
                        }
                    }
                }, 200);
            }
        }, mRecyclerOrder);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                RepoOrderResp.DataBean.ListBean listBean = mDataBeanList.get(position);
                ARouter.getInstance()
                        .build("/xy/order/repo/detail")
                        .withObject("dataBean", listBean)
                        .navigation();
            }
        });

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.btn_delete_order: {
                        String id = mDataBeanList.get(position).id;
                        mPresenter.delOrder(id, position);
                    }
                    break;
                    case R.id.image_more: {
                        String projectId = mDataBeanList.get(position).projectId;
                        ARouter.getInstance().build("/xy/operation/record")
                                .withString("projectId", projectId)
                                .navigation();
                    }
                    break;
                    default:
                        break;
                }
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.aid_prompt_color, R.color.colorBackground);
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        pageNum = 1;
        mPresenter.takeView(this);
        mPresenter.loadRepoOrderList(pageNum);
    }

    @Override
    protected void initData() {
    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        mPresenter.takeView(this);
        mPresenter.loadRepoOrderList(pageNum);
    }

    @Override
    public void loadRepoOrderListSuccess(RepoOrderResp.DataBean dataBean) {
        mSwipeRefreshLayout.setRefreshing(false);
        mProgressBar.setVisibility(View.GONE);
        mRecyclerOrder.setVisibility(View.VISIBLE);

        List<RepoOrderResp.DataBean.ListBean> list = dataBean.list;
        if (pageNum == 1) {
            mDataBeanList.clear();
        }
        mDataBeanList.addAll(list);
        if (pageNum >= dataBean.pages) {
            isEnd = true;
        } else {
            isEnd = false;
            pageNum += 1;
        }
        mAdapter.setNewData(mDataBeanList);
        mAdapter.loadMoreComplete();
        mSwipeRefreshLayout.setEnabled(true);
    }

    @Override
    public void loadRepoOrderListFailure() {
        mSwipeRefreshLayout.setRefreshing(false);
        mProgressBar.setVisibility(View.GONE);
        mRecyclerOrder.setVisibility(View.VISIBLE);
    }

    @Override
    public void delOrderSuccess(BaseResp resp, int position) {
        if (null != this.getActivity()) {
            ToastUtil.showTip(this.getActivity(), "删除订单成功！！！");
        }
        mDataBeanList.remove(position);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void delOrderFailure(String msg) {
        if (null != this.getActivity()) {
            ToastUtil.showTip(this.getActivity(), msg);
        }
        Timber.e("delOrderFailure");
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.bindToLifecycle();
    }
}
